//
//  SearchBleDeviceVC.swift
//  newSwift
//
//  Created by Li on 2023/12/11.
//

import UIKit

class SearchBleDeviceVC: BaseViewController {
    
    /// datasource
    var datasource: [BLEDevice] = []
    
    /// tableView
    lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: UITableViewCell.self)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        BluetoothManager.shared.discoverPeripheralCallBack = {
            [weak self] device in
            self?.didDiscoverDevice(device: device)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        BluetoothManager.shared.scan()
    }
    
    override func layoutViews() {
        super.layoutViews()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.bottom.right.left.equalToSuperview()
        }
    }
    
    func didDiscoverDevice(device: BLEDevice) {
        datasource.append(device)
        tableView.reloadData()
    }
    
}

extension SearchBleDeviceVC: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        datasource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        60
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: UITableViewCell.self)
        
        let device = datasource[indexPath.row]
        
        cell.textLabel?.text = device.peripheral?.name
//        cell.detailTextLabel?.text = String(format: "%d", (datasource[indexPath.row].macAddress)!)
         
        return cell
    }
}
